package com.manage.service.impl;

import com.manage.dao.BuildingDao;
import com.manage.dao.RoomDao;
import com.manage.dao.impl.BuildingDaoImpl;
import com.manage.dao.impl.RoomDaoImpl;
import com.manage.pojo.Building;
import com.manage.pojo.ResultData;
import com.manage.service.BuildingService;
import com.manage.utils.JDBCUtils;

import java.sql.SQLException;
import java.util.List;

public class BuildingServiceImpl implements BuildingService {
    @Override
    public ResultData selectByPage(String page, String limit) {
        //获取分页条件
        int j = Integer.parseInt(page);
        int k = Integer.parseInt(limit);

        //处理数据库数据
        BuildingDao buildingDao=new BuildingDaoImpl();


        try {
            List<Building> buildingAllPage= buildingDao.findAll(j,k);
            List<Building> buildingDaoAll = buildingDao.findAll();

//          返回结果
            return new ResultData(0,"查询成功",buildingAllPage,buildingDaoAll.size());

        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return  new ResultData(10000,"数据异常");
        }

    }
    @Override
    public ResultData removeOneByBid(String bid) {
        if (bid==null||bid.isEmpty()){
            return    new ResultData(10000,"数据有误");
        }
        int b = Integer.parseInt(bid);

        BuildingDao buildingDao=new BuildingDaoImpl();
        RoomDao roomDao=new RoomDaoImpl();

        int i1=0,i2=0;
        try {
            JDBCUtils.begin();

            i1 = buildingDao.deleteBuildingByBid(b);
            i2 = roomDao.deleteroomByBid(b);
            JDBCUtils.commit();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            JDBCUtils.rollBack();
            return new ResultData(10000,"删除异常");
        }
        if(i1==0){
            return new ResultData(10000,"删除失败");
        }
        return new ResultData(0,"共删除"+i1+"条楼栋数据"+i2+"条房间数据");
    }

    @Override
    public ResultData addBuilding(Building building) {
        ResultData resultData = null;
        try {
            JDBCUtils.begin();
            BuildingDao buildingDao=new BuildingDaoImpl();
            int count = buildingDao.insertBuilding(building);

            if(count > 0){
                resultData = new ResultData(0,"添加成功");
            }else{
                resultData = new ResultData(10000,"添加失败");
            }
            JDBCUtils.commit();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            JDBCUtils.rollBack();
            resultData = new ResultData(10000,"添加异常");
        }
        return resultData;
    }

}
